{block name="main"}
<!-- page -->
<form class="form-horizontal form-validate widthFixedForm">
    <div class="screen-title">
        <span class="text">规则设置</span>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label"><span class="text-bright">*</span>适用范围</label>
        <div class="col-md-5">
            <label class="radio-inline">
                <input type="radio" name="shop_range_type" id="shop_range_type_1" value="1" checked> 自营店
            </label>
            <label class="radio-inline">
                <input type="radio" name="shop_range_type" id="shop_range_type_2" value="2"> 全平台
            </label>
            <div class="mb-0 help-block">自营店只能选择自营商品，全平台则是商城（自营、入驻）的所有商品。</div>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label"><span class="text-bright">*</span>主动领取</label>
        <div class="col-md-5">
            <div class="switch-inline">
                <input type="checkbox" name="is_fetch" id="is_fetch" checked>
                <label for="is_fetch" class=""></label>
            </div>

        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label"><span class="text-bright">*</span>优惠券名称</label>
        <div class="col-md-5">
            <input type="text" id="coupon_name" class="form-control" name="coupon_name" required autocomplete="off">
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label"><span class="text-bright">*</span>优惠券类型</label>
        <div class="col-md-5">
            <label class="radio-inline">
                <input type="radio" name="coupon_genre" id="coupon_genre_1" value="1" checked> 无门槛券
            </label>
            <label class="radio-inline">
                <input type="radio" name="coupon_genre" id="coupon_genre_2" value="2"> 满减券
            </label>
            <label class="radio-inline">
                <input type="radio" name="coupon_genre" id="coupon_genre_3" value="3"> 折扣券
            </label>
            <div class="mb-0 help-block">无门槛券可直接使用，满减券与折扣券需要满足一定金额使用</div>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label"><span class="text-bright">*</span>面值</label>
        <div class="col-md-5">
            <div id="coupon_genre_type_1">
                <div class="input-group w-200">
                    <input type="number" id="no_limit_money" name="no_limit_money" class="form-control" min="0" required>
                    <div class="input-group-addon">元</div>
                </div>
                <div class="mb-0 help-block">优惠的金额或折扣</div>
            </div>
            <div id="coupon_genre_type_2" style="display: none;">
                <div class="input-group">
                    <div class="input-group-addon">满</div>
                    <input type="number" id="reduction_at_least" name="reduction_at_least" class="form-control" min="0">
                    <div class="input-group-addon">元，减</div>
                    <input type="number" id="full_reduction_money" name="full_reduction_money" class="form-control"
                           min="0">
                    <div class="input-group-addon">元</div>
                </div>
                <div class="mb-0 help-block">优惠的金额或折扣</div>
            </div>
            <div id="coupon_genre_type_3" style="display: none;">
                <div class="input-group">
                    <div class="input-group-addon">满</div>
                    <input type="number" id="discount_at_least" name="discount_at_least" class="form-control" min="0">
                    <div class="input-group-addon">元，打</div>
                    <input type="number" id="discount" name="discount" class="form-control" min="0">
                    <div class="input-group-addon">折</div>
                </div>
                <div class="mb-0 help-block">优惠的金额或折扣</div>
            </div>
            
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label"><span class="text-bright">*</span>发放数量</label>
        <div class="col-md-5">
            <div class="input-group w-200">
                <input type="number" id="count" name="count" class="form-control" required min="0" autocomplete="off">
                <div class="input-group-addon">张</div>
            </div>
            <div class="mb-0 help-block">0代表不限制</div>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">每人限领</label>
        <div class="col-md-5">
            <div class="input-group w-200">
                <input type="number" class="form-control" name="max_fetch" id="max_fetch" min="0">
                <div class="input-group-addon">张</div>
            </div>
            <div class="mb-0 help-block">0代表不限制</div>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label"><span class="text-bright">*</span>领券时间</label>
        <div class="col-md-8">
            <div class="v-datetime-input-control">
                <label for="receive_coupon_time">
                    <input type="text" class="form-control" id="receive_coupon_time" placeholder="请选择时间" value="" autocomplete="off" name="receive_coupon_time" required> 
                    <i class="icon icon-calendar"></i>
                    <input type="hidden" id="start_receive_time">
                    <input type="hidden" id="end_receive_time">
                    </label>
            </div>
            <div class="help-block mb-0">开始时间点为选中日期的0:00:00，结束时间点为选中日期的23:59:59</div>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label"><span class="text-bright">*</span>生效时间</label>
        <div class="col-md-8">
            <div class="v-datetime-input-control">
                <label for="effect_time">
                    <input type="text" class="form-control" id="effect_time" placeholder="请选择时间" value="" autocomplete="off" name="effect_time" required>
                    <i class="icon icon-calendar"></i>
                    <input type="hidden" id="start_time">
                    <input type="hidden" id="end_time">
                </label>
            </div>
            <div class="help-block mb-0">开始时间点为选中日期的0:00:00，结束时间点为选中日期的23:59:59</div>
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">优惠券说明</label>
        <div class="col-md-5">
            <textarea class="form-control" name="desc" id="desc" rows="4"></textarea>
        </div>
    </div>

    <div class="screen-title">
        <span class="text">活动商品</span>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">参加活动商品</label>
        <div class="col-md-5">
            <label class="radio-inline">
                <input type="radio" name="range_type" value="1" checked> 所有商品
            </label>
            <label class="radio-inline">
                <input type="radio" name="range_type" value="0"> 部分商品
            </label>
        </div>
    </div>
    <div class="form-group hidden" id="range_type">
        <label class="col-md-2 control-label"></label>
        <div class="col-md-9">
            <div>
                <ul class="nav nav-tabs v-nav-tabs" role="tablist">
                    <li role="presentation" class="active"><a href="#list" aria-controls="list" role="tab"
                                                              data-toggle="tab"
                                                              class="flex-auto-center">商品列表</a></li>
                    <li role="presentation"><a href="#curr" aria-controls="curr" role="tab" data-toggle="tab"
                                               class="flex-auto-center">已选商品</a></li>
                    <div class="input-group search-input-group pull-right">
                        <input type="text" class="form-control" id="search_text" placeholder="商品名称" name="search_text">
                        <span class="input-group-btn"><button class="btn btn-primary" type="button"
                                                              id="search">搜索</button></span>
                    </div>
                </ul>
                <div class="tab-content">
                    <div role="tabpanel" class="tab-pane fade in active" id="list">
                        <table class="table v-table table-auto-center">
                            <thead>
                            <tr>
                                <th>商品信息</th>
                                <th>库存</th>
                                <th>店铺</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="goods_list">
                            </tbody>
                        </table>
                        <input type="hidden" id="page_index" name="page_index">
                        <nav aria-label="Page navigation" class="clearfix">
                            <ul id="page" class="pagination pull-right"></ul>
                        </nav>
                    </div>
                    <div role="tabpanel" class="tab-pane" id="curr">
                        <table class="table v-table table-auto-center">
                            <thead>
                            <tr>
                                <th>商品信息</th>
                                <th>库存</th>
                                <th>店铺</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="selected_goods_list">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="form-group"></div>
    <div class="form-group">
        <label class="col-md-2 control-label"></label>
        <div class="col-md-8">
            <button class="btn btn-primary" type="submit">保存</button>
            <a href="javascript:history.go(-1);" class="btn btn-default">返回</a>
        </div>
    </div>
    <input type="hidden" id="coupon_type_id" name="coupon_type_id"/>
</form>

<!-- page end -->
{/block}
{block name="script"}
<script>
    require(['util', 'utilAdmin'], function (util, utilAdmin) {
        util.layDate('#receive_coupon_time',true,function(value, date, endDate){
            var date1=date.year+'-'+date.month+'-'+date.date;
            var date2=endDate.year+'-'+endDate.month+'-'+endDate.date;
            if(value){
                $('#start_receive_time').val(date1);
                $('#end_receive_time').val(date2);
                $('#receive_coupon_time').parents('.form-group').removeClass('has-error');
            }
            else{
                $('#start_receive_time').val('');
                $('#end_receive_time').val('');
            }
        });
        util.layDate('#effect_time',true,function(value, date, endDate){
            var date1=date.year+'-'+date.month+'-'+date.date;
            var date2=endDate.year+'-'+endDate.month+'-'+endDate.date;
            if(value){
                $('#start_time').val(date1);
                $('#end_time').val(date2);
                $('#effect_time').parents('.form-group').removeClass('has-error');
            }
            else{
                $('#start_time').val('');
                $('#end_time').val('');
            }
        });
        window['coupon_type_info'] = {$coupon_type_info};
        window['post_coupon_type_url'] = "{$addCouponTypeUrl}";
        if (typeof (coupon_type_info) == 'object') {
            window['post_coupon_type_url'] = "{$updateCouponTypeUrl}";
            $("#coupon_type_id").val(coupon_type_info.coupon_type_id);
            $("#coupon_name").val(coupon_type_info.coupon_name);

            if (coupon_type_info.shop_range_type == 1) {
                $("#shop_range_type_1").prop("checked", true);
            } else if (coupon_type_info.shop_range_type == 2) {
                $("#shop_range_type_2").prop("checked", true);
            }

            if (coupon_type_info.is_fetch == 1) {
                $("#is_fetch").attr("checked", true);
            } else if (coupon_type_info.is_fetch == 0) {
                $("#is_fetch").attr("checked", false);
            }

            if (coupon_type_info.coupon_genre == 1) {
                $("#coupon_genre_1").prop("checked", true);
                $("#no_limit_money").val(coupon_type_info.money);
            } else if (coupon_type_info.coupon_genre == 2) {
                $("#coupon_genre_2").prop("checked", true);
                $("#full_reduction_money").val(coupon_type_info.money);
                $("#reduction_at_least").val(coupon_type_info.at_least);
            } else if (coupon_type_info.coupon_genre == 3) {
                $("#coupon_genre_3").prop("checked", true);
                $("#discount").val(coupon_type_info.discount);
                $("#discount_at_least").val(coupon_type_info.at_least);
            }
            $('#coupon_genre_type_' + coupon_type_info.coupon_genre).show().siblings().hide();
            $('#coupon_genre_type_' + coupon_type_info.coupon_genre).find('input').prop('required', true);
            $('#coupon_genre_type_' + coupon_type_info.coupon_genre).show().siblings().find('input').removeAttr('required');
            $("#count").val(coupon_type_info.count);
            $("#max_fetch").val(coupon_type_info.max_fetch);
            $("#start_receive_time").val(utilAdmin.timeStampTurnDate(coupon_type_info.start_receive_time));
            $("#end_receive_time").val(utilAdmin.timeStampTurnDate(coupon_type_info.end_receive_time));
            var val1 = utilAdmin.timeStampTurnDate(coupon_type_info.start_receive_time)+' - '+utilAdmin.timeStampTurnDate(coupon_type_info.end_receive_time);
            $("#receive_coupon_time").val(val1);
            $("#start_time").val(utilAdmin.timeStampTurnDate(coupon_type_info.start_time));
            $("#end_time").val(utilAdmin.timeStampTurnDate(coupon_type_info.end_time));
            var val2 = utilAdmin.timeStampTurnDate(coupon_type_info.start_time)+' - '+utilAdmin.timeStampTurnDate(coupon_type_info.end_time);
            $("#effect_time").val(val2);

            $("#desc").val(coupon_type_info.desc);

            if (coupon_type_info.range_type == 0) {
                $('#range_type').removeClass('hidden')
                $("input[type=radio][name='range_type'][value=0]").prop("checked", true);
                var goods_html = '';
                $.each(coupon_type_info.goods_list, function (k, v) {
                    if (v.goods_name){
                        goods_html += '<tr id="html_' + v.goods_id + '" goodsid="' + v.goods_id + '" data-shop-id="' + v.shop_id + '">';
                        goods_html += '<td>';
                        goods_html += '<div class="media text-left">';
                        goods_html += '<div class="media-left">';
                        goods_html += '<div>';
                        if (v.picture_info != null) {
                            goods_html += '<img src="' + __IMG(v.picture_info.pic_cover_micro) + '" width="60" height="60"></div></th>';
                        } else {
                            goods_html += '<img src="__ROOT__/" width="60" height="60"></div></th>';
                        }
                        goods_html += '</div>';
                        goods_html += '<div class="media-body max-w-300">';
                        goods_html += '<div class="line-2-ellipsis"><a href="' + __URLS('SHOP_MAIN/goods/goodsinfo&goodsid=' + v.goods_id) + '" target="_blank" class="new-window" title="' + v.goods_name + '">' + v.goods_name + '</a></div>';
                        goods_html += '</div>';
                        goods_html += '</div>';
                        goods_html += '</td>';
                        goods_html += '<td>';
                        goods_html += v.stock;
                        goods_html += '</td>';
                        goods_html += '<td>';
                        goods_html += v.shop_name;
                        goods_html += '</td>';
                        goods_html += '<td>';
                        goods_html += '<a class="btn btn-default btn-sm cancel" id="id_' + v.goods_id + '" href="javascript:;">取消参加</a>';
                        goods_html += '<input type="hidden" name="goods_id" value="' + v.goods_id + '">';
                        goods_html += '</td>';
                        goods_html += '</tr>';
                    }
                })
                $("#selected_goods_list").html(goods_html);
            }
        } else {
            $("button[type=submit]").html('添加')
            // 保存编辑时选择的商品id，防止重新加载商品列表时，已选中的商品为没选中，然后被重复选中
            coupon_type_info = {}
            coupon_type_info.goods_id_array = [];
        }

        util.initPage(LoadingInfo);

        $('#search').on('click', function () {
            LoadingInfo(1);
        });

        // 切换全平台和自营店类型时，如果有打开活动指定商品，重新获取对应的全平台和自营店商品
        $("input[name='shop_range_type']").on('change', function () {
            LoadingInfo(1)
            if ($("input[name='shop_range_type']:checked").val() == 1) {
                // 在全平台选择其他店铺的商品，切换到自营店,删除选择的店铺的商品
                $("#selected_goods_list tr").each(function () {
                    var shop_id = $(this).data('shop-id')
                    var goods_id = $(this).attr('goodsid')
                    if (shop_id != 0) {
                        $(this).remove();
                        coupon_type_info.goods_id_array.splice($.inArray(parseInt(goods_id), coupon_type_info.goods_id_array), 1)
                    }
                })
            }

        })

        //加载筛选数据
        function LoadingInfo(page_index) {
            var search_text = $("#search_text").val();
            var shop_range_type = $("input[name='shop_range_type']:checked").val();
            $.ajax({
                type: "post",
                url: "{:__URL('PLATFORM_MAIN/goods/getserchgoodslist')}",
                data: {
                    "page_index": page_index,
                    "page_size": $("#showNumber").val(),
                    "search_text": search_text,
                    "shop_range_type": shop_range_type,
                },
                success: function (data) {
                    $data_array = data['data'];
                    var html = '';
                    if (data['data'].length > 0) {
                        for (var i = 0; i < data['data'].length; i++) {
                            html += '<tr id="html_' + data['data'][i]["goods_id"] + '" goodsid="' + data['data'][i]["goods_id"] + '" data-shop-id="' + data['data'][i]["shop_id"] + '">';
                            html += '<td>';
                            html += '<div class="media text-left">';
                            html += '<div class="media-left">';
                            html += '<div>';
                            if (data['data'][i]["picture_info"] != null) {
                                html += '<img src="' + __IMG(data['data'][i]["picture_info"]['pic_cover_micro']) + '" width="60" height="60"></div></th>';
                            } else {
                                html += '<img src="__ROOT__/" width="60" height="60"></div></th>';
                            }
                            html += '</div>';
                            html += '<div class="media-body max-w-300">';
                            html += '<div class="line-2-ellipsis"><a href="' + __URLS('SHOP_MAIN/goods/goodsinfo&goodsid=' + data['data'][i]["goods_id"]) + '" target="_blank" class="new-window" title="' + data['data'][i]["goods_name"] + '">' + data['data'][i]["goods_name"] + '</a></div>';
                            html += '</div>';
                            html += '</div>';
                            html += '</td>';
                            html += '<td>';
                            html += data['data'][i]["stock"];
                            html += '</td>';
                            html += '<td>';
                            html += data['data'][i]["shop_name"];
                            html += '</td>';
                            html += '<td>';
                            if ($.inArray(data['data'][i]["goods_id"], coupon_type_info.goods_id_array) == -1) {
                                html += '<a class="btn btn-default btn-sm btn-primary join" id="id_' + data['data'][i]["goods_id"] + '" href="javascript:;">参加活动</a>';
                            } else {
                                html += '<a class="btn btn-default btn-sm cancel" id="id_' + data['data'][i]["goods_id"] + '" href="javascript:;">取消参加</a>';
                            }
                            html += '<input type="hidden" name="goods_id" value="' + data['data'][i]["goods_id"] + '">';
                            html += '</td>';
                            html += '</tr>';
                        }
                    } else {
                        html += '<tr align="center"><th colspan="4">暂无符合条件的数据记录</th></tr>';
                    }
                    $("#goods_list").html(html);
                    $('#page').paginator('option', {
                        totalCounts: data['total_count']  // 动态修改总数
                    });
                }
            });
        }

        //提交数据
        var flag = false;
        util.validate($('.form-validate'), function (form) {
            var coupon_type_id = $("#coupon_type_id").val();
            var coupon_name = $("#coupon_name").val();
            var coupon_genre = $("input[name='coupon_genre']:checked").val();
            var shop_range_type = $("input[name='shop_range_type']:checked").val();
            var money;
            var discount;
            var at_least;

            if (coupon_genre == 1) {
                money = $("#no_limit_money").val();
                at_least = 0;
                discount = 0;
            } else if (coupon_genre == 2) {
                money = $("#full_reduction_money").val();
                at_least = $("#reduction_at_least").val();
                discount = 0;
            } else if (coupon_genre == 3) {
                money = 0;
                at_least = $("#discount_at_least").val();
                discount = $("#discount").val();
            }
            var count = $("#count").val();
            var max_fetch = $("#max_fetch").val();
            var range_type = $("input[name='range_type']:checked").val();
            var start_receive_time = $("#start_receive_time").val();
            var end_receive_time = $("#end_receive_time").val();
            var start_time = $("#start_time").val();
            var end_time = $("#end_time").val();
            var is_fetch = $("input[name='is_fetch']").is(':checked')?1:0;
            var desc = $("#desc").val();
            var obj = $("#selected_goods_list tr");
            var goods_id_array = '';
            obj.each(function (i) {
                goods_id_array += ',' + obj.eq(i).attr("goodsid");
            });
            goods_id_array = goods_id_array.substring(1);
            if (range_type == 0 && goods_id_array === '') {
                util.message('请选择商品', 'info', function () {
                });
                return;
            }
            if (parseInt(count) < parseInt(max_fetch) && parseInt(count) != 0) {
                util.message('每人最大领取数目要小于发放数量！', 'info', function () {
                    $('#max_fetch').focus();
                });
                return false;
            }
            if (flag) {
                return;
            }

            if (util.DateTurnTime(start_receive_time) > util.DateTurnTime(end_receive_time)) {
                $("#receive_coupon_time").focus();
                util.message("开始领券时间大于结束时间");
                return;
            }
            if (util.DateTurnTime(start_time) > util.DateTurnTime(end_time)) {
                $("#effect_time").focus();
                util.message("开始生效时间大于结束时间");
                return;
            }
            if (util.DateTurnTime(end_receive_time) > util.DateTurnTime(end_time)) {
                util.message("最大领取时间应小于最大使用时间");
                return;
            }


            flag = true;
            $.ajax({
                type: "post",
                url: post_coupon_type_url,
                data: {
                    'coupon_type_id': coupon_type_id,
                    'shop_range_type': shop_range_type,
                    'coupon_name': coupon_name,
                    'coupon_genre': coupon_genre,
                    'money': money,
                    'count': count,
                    'at_least': at_least,
                    'discount': discount,
                    'max_fetch': max_fetch,
                    'range_type': range_type,
                    'start_receive_time': start_receive_time,
                    'end_receive_time': end_receive_time,
                    'start_time': start_time,
                    'end_time': end_time,
                    'is_fetch': is_fetch,
                    'desc': desc,
                    'goods_list': goods_id_array,
                },
                success: function (data) {
                    if (data["code"] > 0) {
                        util.message(data["message"], 'success', "{:__URL('ADDONS_MAINcouponTypeList')}");
                    } else {
                        util.message(data["message"], 'danger');
                    }
                }
            });
        });

        //加入商品
        $('body').on('click', '.join', function () {
            var id = $(this).next($("input[name='goods_id']")).val();
            var shop_id = $(this).parents('tr').data('shop-id')
            $(this).removeClass('join');
            $(this).parent().html('<a class="btn btn-default btn-sm cancel" id="id_' + id + '" href="javascript:;">取消参加</a><input type="hidden" name="goods_id" value="' + id + '">');
            var html = $('#html_' + id).html();
            $("#selected_goods_list").append('<tr id="html_' + id + '" goodsid="' + id + '" data-shop-id="' + shop_id + '">' + html + '</tr>');
            coupon_type_info.goods_id_array.push(parseInt(id));
        })

        //取消参加
        $('body').on('click', '.cancel', function () {
            var id = $(this).next($("input[name='goods_id']")).val();
            $('#selected_goods_list #html_' + id + '').remove();
            $('#id_' + id + '').removeClass('cancel');
            $('#id_' + id + '').addClass('join btn-primary');
            $('#id_' + id + '').html("参加活动");
            coupon_type_info.goods_id_array.splice($.inArray(parseInt(id), coupon_type_info.goods_id_array), 1)
        })

        $("input[name='coupon_genre']").on('change', function () {
            $('#coupon_genre_type_' + $(this).val()).show().siblings().hide();
            $('#coupon_genre_type_' + $(this).val()).find('input').prop('required', true);
            $('#coupon_genre_type_' + $(this).val()).show().siblings().find('input').removeAttr('required');
        })

        $('input[name=range_type]').on('change', function () {
            if ($(this).val() == 0) {
                $('#range_type').removeClass('hidden');
            } else {
                $('#range_type').addClass('hidden');
            }
        })
    })
</script>
{/block}
